<template>
  <div class="create-post-page">
    <h4>新建文章</h4>
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <validate-input
          :rules="titleRules"
          v-model="titleVal"
          placeholder="请输入文章标题"
          type="text"
        />
      </div>
      
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <validate-input
          rows="10"
          type="text"
          tag="textarea"
          placeholder="请输入文章详情"
          :rules="contentRules"
          v-model="contentVal"
        />
      </div>

      <template #submit>
        <button class="btn btn-primary btn-large">发表文章</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import ValidateInput, { RulesProp } from "../components/VaildateInput.vue";
import ValidateForm from "../components/ValidateForm.vue";
import { GlobalDataProps, PostProps } from "../store";
export default defineComponent({
  name: "Login",
  components: {
    ValidateInput,
    ValidateForm,
  },

  setup() {
    // data数据添加双向数据绑定
    const titleVal = ref("");

    // 实例化路由
    const router = useRouter();

    // 实例化vuex
    const store = useStore<GlobalDataProps>();

    // 约束文章标题必填
    const titleRules: RulesProp = [
      { type: "required", message: "文章标题不能为空" },
    ];

    // 获取输入的文章详情
    const contentVal = ref("");

    // 约束文章内容必填
    const contentRules: RulesProp = [
      { type: "required", message: "文章详情不能为空" },
    ];

    // 点击新建文章跳转
    const onFormSubmit = (result: boolean) => {
      // 文章和详情不为空的情况下，才能进入
      if (result) {
        // 从 user 解构出 columnId = 1
        const { columnId } = store.state.user;

        // 判断 columnId存在，就继续操作
        if (columnId) {
          // newPost 拿到发表文章中的所有内容
          const newPost: PostProps = {
            // 总毫秒数
            id: new Date().getTime(),

            // 文章标题
            title: titleVal.value,
      
            // 文章详情内容
            content: contentVal.value,

            // 代表专栏1的内容
            columnId,

            // toLocaleString() 根据本地时间把 Date 对象转换为字符串
            createdAt: new Date().toLocaleString(),
          };

          // 触发 Vuex中的 createPost,并把发表文章中的所有内容传递过去
          store.commit("createPost", newPost);

          // 文章创建完毕之后，会自动跳转到 columnId 对应的专栏页
          router.push({ name: "column", params: { id: columnId } });
        }
      }
    };
    return {
      titleRules,
      titleVal,
      contentVal,
      contentRules,
      onFormSubmit,
    };
  },
});
</script>